<?php

class Welcome extends CI_Controller {

	function __construct(){
		parent::__construct();
		//$this->load->library('FAL_front', 'fal_front'); // Attach one of freakauth libraries
		$this->load->library('form_validation');
		//$this->load->library('session');
		$this->load->model('user_man_model');
	}//end constructor
	
	function index(){
		if( $this->session->userdata('username') == null) {
			$this->login();
		}
		else
		{
			$this->home();			
		}  
	}//end index
	
	function login(){

		//$this->session->sess_destroy(); 		
		//$valid = false; 
		
		$this->form_validation->set_rules('user_name', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_cek_password');
		$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
						
		if($this->form_validation->run() == TRUE)
		{
			$username = $this->input->post('user_name');
			$password = md5($this->input->post('password'));
		
			$users	= $this->user_man_model->get_user($username);
		
			foreach ($users->result() as $row){	
				if($username == $row->USER_LOGIN && $password == $row->USER_PASSWORD){
					//$valid = true;
					$newdata = array(
						'userid' => $row->USER_ID,
						'username' => $username,
						'nama' => $row->USER_NAMA
						);
					$this->session->set_userdata($newdata);
					break;
				}			
			}
			
			$this->home();
		
		}
		else 
		{
			$this->load->view('welcome');
		} // end foreach
			 
	}//end login
	
	function home()
	{
		if($this->session->userdata('username') == null)
		{
			redirect('welcome');
		}
		else{
			$data['content'] = $this->load->view('home','null',TRUE);
			$this->load->view('main',$data);
        }
	}//end home

	function cek_password()
	{
		$username = $this->input->post('user_name');
		$password = md5($this->input->post('password'));
		
		$users	= $this->user_man_model->get_user($username);

		foreach ($users->result() as $row){

			if( $password == $row->USER_PASSWORD){
				return TRUE;		
			}
			else{
				$this->form_validation->set_message('cek_password', 'Password Salah !!');
				return FALSE;
			}
		}// end foreach

	}
        
	function logout()
	{		
		$this->session->sess_destroy();
		$this->login();	
	}
	
}//end class

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
